/**
 * @Date: 2022-03-10 11:57:09
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-03-13 17:23:13
 * @FilePath: \zhihuReal\controllers\topicCtl.js
 * @Description: 话题控制器
 */

const {
    SuccessModel,
    ErrorModel
} = require('../res-model/index')
const Topic = require('../model/topicMdl')
const User = require('../model/usersMdl')
const Question = require('../model/questionMdl')
//获取话题列表
const topicList = async (ctx) => {
    //分页
    const {
        limit = 10, page = 1
    } = ctx.query
    const pagenum = Math.max(+page, 1) - 1
    const limitnum = Math.max(+limit, 1)
    //模糊搜索
    const list = await Topic.find({
        name: new RegExp(ctx.query.keyword)
    }).limit(limitnum).skip(pagenum * limitnum)
    ctx.body = new SuccessModel(list)
}
//获取单个话题
const oneTopic = async (ctx) => {
    const {
        fields = ''
    } = ctx.query
    const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('')
    const topic = await Topic.findById(ctx.params.id).select(selectFields)
    if (!topic) {
        ctx.throw(404, '用户不存在')
    } else {
        ctx.body = new SuccessModel(topic)
    }
}
//创建话题
const createTopic = async (ctx) => {
    ctx.verifyParams({
        name: {
            type: 'string',
            required: true
        },
        imgUrl: {
            type: 'string',
            required: false
        },
        desc: {
            type: 'string',
            required: false
        }
    })
    const newTopic = await Topic.create(ctx.request.body)
    ctx.body = new SuccessModel()
}
//更新话题
const updateTopic = async (ctx) => {
    ctx.verifyParams({
        name: {
            type: 'string',
            required: false
        },
        imgUrl: {
            type: 'string',
            required: false
        },
        desc: {
            type: 'string',
            required: false
        }
    })
    const newTopic = await Topic.findByIdAndUpdate(ctx.params.id, ctx.request.body)
    ctx.body = new SuccessModel(newTopic)
}
const topicFollowerList = async (ctx) => {
    const list = await User.find({
        followingTopics: ctx.params.id
    })
    ctx.body = new SuccessModel(list)
}
//列出问题
const listQuestions = async (ctx) => {
    const list = await Question.find({
        topics: ctx.params.id
    })
    ctx.body = new SuccessModel(list)
}
module.exports = {
    topicList,
    oneTopic,
    createTopic,
    updateTopic,
    topicFollowerList,
    listQuestions
}